package cn.jinjimi.app.poster.presenter;

import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.domain.data.dto.PostersInfoDto;
import cn.jinjimi.domain.ServiceManager;
import cn.jinjimi.domain.store.PosterStore;
import cn.jinjimi.app.poster.interfaces.PosterFragmentView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import bolts.Continuation;
import bolts.Task;

/**
 * Created by lforxeverc on 16/9/26.
 */

public class PosterPresenter {
    public List<Integer> reqPage = new ArrayList<>();
    public static final int LIMIT = 12;
    public static final int DEFAULT_PAGE = 1;
    private PosterFragmentView mView;
    private int categoryCode, subCategoryCode;
    private String productId;

    public PosterPresenter(PosterFragmentView view, int categoryCode, int subCategoryCode, String productId) {
        this.mView = view;
        this.categoryCode = categoryCode;
        this.subCategoryCode = subCategoryCode;
        this.productId = productId;
    }

    public void loadAtPage(final Integer page) {
        if (reqPage.contains(page)) return;
        reqPage.add(page);
        final Map<String, Object> map = new HashMap<>();
        if (categoryCode != -1) {
            map.put("category_code", categoryCode);
        }
        if (subCategoryCode != -1) {
            map.put("sub_category_code", subCategoryCode);
        }
        if (!StringUtils.isEmpty(productId)) {
            map.put("product_id", productId);
        }
        map.put("limit", LIMIT);
        map.put("page", page);
        Task.callInBackground(new Callable<PostersInfoDto>() {
            @Override
            public PostersInfoDto call() throws Exception {
                return ServiceManager.getService(PosterStore.class).fetchPosterTemplates(map);
            }
        }).continueWith(new Continuation<PostersInfoDto, Object>() {
            @Override
            public Object then(Task<PostersInfoDto> task) throws Exception {
                reqPage.remove(page);
                PostersInfoDto info = task.getResult();
                if (info.isOk) {
                    mView.loadSuccess(page, info.data, (info.data == null || info.data.posters == null || info.data.posters.size() < LIMIT));
                } else {
                    mView.loadFail(page, "加载失败，请稍后再试");
                }
                return null;
            }
        }, Task.UI_THREAD_EXECUTOR);
    }

}
